Java中取多个集合的交集 您所在的位置:网站首页 java 两个list取差集 Java中取多个集合的交集

Java中取多个集合的交集

2023-08-22 17:29| 来源: 网络整理| 查看: 265

Java中取多个集合的交集

集合 Collection 接口中定义了 retainAll()方法

retainAll()

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

简单来说,该方法目的是取当前集合 和参数指定集合的一个交集,并修改当前集合,仅保留交集元素。

下图是集合类框架的一个架构图: 在这里插入图片描述

通过这个架构图,可以在大脑中对集合这块的类有个清晰的定位。

抽象类 AbstractCollection 中对 retainAll() 方法进行了实现。 使用Set集合的 retainAll() 方法,其实就是调用了AbstractCollection中的 retainAll()方法。

其底层其实使用的 contains() 方法进行判断元素是否存在集合中。对于当前集合中的元素进行遍历,判断每个元素是否存在于参数集合中,若不存在则从当前集合中移除该元素,最终保留的就是两个集合共有的元素。

public boolean retainAll(Collection c) { Objects.requireNonNull(c); boolean modified = false; Iterator it = iterator(); while (it.hasNext()) { if (!c.contains(it.next())) { it.remove(); modified = true; } } return modified; }

对于 ArrayList 类,对 retainAll() 方法进行了重写。其中的核心思路是一样的。

public boolean retainAll(Collection c) { Objects.requireNonNull(c); return batchRemove(c, true); } private boolean batchRemove(Collection c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { for (; r System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i { resultSet.retainAll(item); }); //resultSet 结果仅包含 1

再复杂的东西都是由简单的东西组成的,只因量变达到质变。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有